using System;
using System.Web;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using Sedna.Core.Support;

namespace Sedna.Core.Controls.Actions
{
	public class ValidateComparisonAction : AbstractValidationAction
	{
		public const String EQ = "Eq";
		public const String LT = "Lt";
		public const String GT = "Gt";

		private bool isNegation;
		private String compareOperation = EQ;
		private String leftValueContextKey;
		private String rightValueContextKey;

		#region Properties

		public bool IsNegation
		{
			get { return isNegation;}
			set { isNegation = value;}
		}

		/// <summary>
		/// Possible values are Eq, Lt, Gt. Eq - is default value.
		/// For Lt and Gt operations comparison objects in context must realize IComparable interface.
		/// </summary>
		public String CompareOperation
		{
			get { return compareOperation;}
			set { compareOperation = value;}
		}

		public String LeftValueContextKey
		{
			get { return leftValueContextKey;}
			set { leftValueContextKey = value;}
		}

		public String RightValueContextKey
		{
			get { return rightValueContextKey;}
			set { rightValueContextKey = value;}
		}

		#endregion

		protected override bool Validate(IExecutionContext executionContext)
		{
			Assert.IsTrue(executionContext[LeftValueContextKey] is IComparable, "Can`t validate. Object must realize IComparable interface.");
			Assert.IsTrue(LT.Equals(CompareOperation) || EQ.Equals(CompareOperation) || GT.Equals(CompareOperation), "Can`t validate. Unknown comparison operation.");

			int result = ((IComparable)executionContext[LeftValueContextKey]).CompareTo(executionContext[RightValueContextKey]);
			
			bool isValid = ((LT.Equals(CompareOperation) && result < 0) || (EQ.Equals(CompareOperation) && result == 0) ||(GT.Equals(CompareOperation) && result > 0));

			if (IsNegation)
			{
				return !isValid;
			}

			return isValid;
		}
	}
}
